package com.android.systemui.ios.wall;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.systemui.ios.R;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import java.util.Comparator;
import java.util.Arrays;

public class IpAddNewWallpaperLayout extends FrameLayout {
    private RecyclerView mRecyclerFeatured;
    private RecyclerView mRecyclerWeather;
    private RecyclerView mRecyclerEmoji;
    private RecyclerView mRecyclerCollections;
    private RecyclerView mRecyclerColor;
    private RecyclerView mRecyclerShortcut;

    private IconAdapter mAdapterFeatured;
    private IconAdapter mAdapterWeather;
    private IconAdapter mAdapterEmoji;
    private IconAdapter mAdapterCollections;
    private IconAdapter mAdapterColor;
    private IconAdapter mAdapterShortcut;

    private final List<ItemSetting> mListFeatured = new ArrayList<>();
    private final List<ItemSetting> mListWeather = new ArrayList<>();
    private final List<ItemSetting> mListEmoji = new ArrayList<>();
    private final List<ItemSetting> mListCollections = new ArrayList<>();
    private final List<ItemSetting> mListColor = new ArrayList<>();
    private final List<ItemSetting> mListShortcut = new ArrayList<>();

    private final LinearLayoutManager mLayoutManagerFeatured;
    private final LinearLayoutManager mLayoutManagerWeather;
    private final LinearLayoutManager mLayoutManagerEmoji;
    private final LinearLayoutManager mLayoutManagerCollections;
    private final LinearLayoutManager mLayoutManagerColor;
    private final LinearLayoutManager mLayoutManagerShortcut;

    private List<File> mFileWallpaper;

    private final int mScreenHeight;
    private Runnable mOnSetRunnable;
    private ScrollView mScrollView;
    private IpSetWallpaperLayout mSetWallpaperLayout;
    private SettingViewItemCallback mAddCallback;

    public IpAddNewWallpaperLayout(Context context) {
        this(context, null, 0);
    }

    public IpAddNewWallpaperLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IpAddNewWallpaperLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
        mLayoutManagerFeatured = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        mLayoutManagerWeather = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        mLayoutManagerEmoji = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        mLayoutManagerCollections = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        mLayoutManagerColor = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        mLayoutManagerShortcut = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        findViewById(android.R.id.closeButton).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                animate().translationY(mScreenHeight + 10).alpha(0.0f).setDuration(400).start();

                if (mAddCallback != null)
                    mAddCallback.setMode(1);
            }
        });

        mScrollView = (ScrollView) findViewById(R.id.add_wallpaper_scroll_view);
        mSetWallpaperLayout = (IpSetWallpaperLayout) findViewById(R.id.set_wallpaper_layout);
        mSetWallpaperLayout.setOnSetRunnable(new Runnable() {

            @Override
            public void run() {
                if (mOnSetRunnable != null) {
                    mOnSetRunnable.run();
                }
            }
        });

        initAllData(getResources());
        mAdapterFeatured = new IconAdapter(mListFeatured) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };
        mAdapterWeather = new IconAdapter(mListWeather) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };
        mAdapterEmoji = new IconAdapter(mListEmoji) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };
        mAdapterCollections = new IconAdapter(mListCollections) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };
        mAdapterColor = new IconAdapter(mListColor) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };
        mAdapterShortcut = new IconAdapter(mListShortcut) {

            @Override
            public void onItemClicked(ItemSetting data) {
                postWallpaperItemClicked(data.getType(), data.getThumPath(), data.getBitmapPath());
            }
        };

        mRecyclerFeatured = (RecyclerView) findViewById(R.id.recycler_featured);
        mRecyclerWeather = (RecyclerView) findViewById(R.id.recycler_weather);
        mRecyclerEmoji = (RecyclerView) findViewById(R.id.recycler_emoji);
        mRecyclerCollections = (RecyclerView) findViewById(R.id.recycler_collections);
        mRecyclerColor = (RecyclerView) findViewById(R.id.recycler_color);
        mRecyclerShortcut = (RecyclerView) findViewById(R.id.recycler_shortcut_icon);

        mRecyclerFeatured.setLayoutManager(mLayoutManagerFeatured);
        mRecyclerFeatured.setAdapter(mAdapterFeatured);

        mRecyclerWeather.setLayoutManager(mLayoutManagerWeather);
        mRecyclerWeather.setAdapter(mAdapterWeather);

        mRecyclerEmoji.setLayoutManager(mLayoutManagerEmoji);
        mRecyclerEmoji.setAdapter(mAdapterEmoji);

        mRecyclerCollections.setLayoutManager(mLayoutManagerCollections);
        mRecyclerCollections.setAdapter(mAdapterCollections);

        mRecyclerColor.setLayoutManager(mLayoutManagerColor);
        mRecyclerColor.setAdapter(mAdapterColor);

        mRecyclerShortcut.setLayoutManager(mLayoutManagerShortcut);
        mRecyclerShortcut.setAdapter(mAdapterShortcut);
    }

    private void postWallpaperItemClicked(int type, String thumbpath, String wallpaperpath) {
        if (mAddCallback != null) {
            mAddCallback.userActivity();
            if (mAddCallback.getMode() != 2) return;
            mAddCallback.setMode(3);
        }

        mSetWallpaperLayout.setAlpha(0.0f);
        mSetWallpaperLayout.setVisibility(VISIBLE);
        mSetWallpaperLayout.animate().alpha(1.0f).start();
        mSetWallpaperLayout.setPrepareSetWallpaper(type, thumbpath, wallpaperpath);

        findViewById(R.id.btn_set_wallpaper_cancel).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_set_wallpaper_done).setVisibility(View.VISIBLE);
    }

    public void entryScreen() {
        setAlpha(0.0f);
        setTranslationY(mScreenHeight + 10);
        scrollFullUp();
        mSetWallpaperLayout.entryScreen();
    }

    public void scrollFullUp() {
        mScrollView.fullScroll(View.FOCUS_UP);
    }

    public void setOnSetRunnable(Runnable runnable) {
        mOnSetRunnable = runnable;
    }

    private void orderByName(String filePath, boolean isThumbs, boolean isLive) {
        if (isLive)
            filePath = filePath + "live/";

        File folder = new File(filePath);
        File[] fileArray = folder.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                if (pathname != null && pathname.isFile()) {
                    String name = pathname.getName();
                    if (isLive) {
                        if (isThumbs)
                            return name.startsWith("live_thumb_");
                        else
                            return name.startsWith("live_wall_");
                    } else {
                        if (isThumbs)
                            return name.startsWith("thumb_");
                        else
                            return name.startsWith("wallpaper_");
                    }
                }
                return false;
            }
        });

        if (fileArray != null) {
            mFileWallpaper = Arrays.asList(fileArray);
            mFileWallpaper.sort(new Comparator<File>() {

                @Override
                public int compare(File o1, File o2) {
                    if (o1.isDirectory() && o2.isFile())
                        return -1;
                    if (o1.isFile() && o2.isDirectory())
                        return 1;
                    return o1.getName().compareTo(o2.getName());
                }
            });
        }
    }

    private void initAllData(Resources res) {
        mListShortcut.clear();
        mListFeatured.clear();
        mListWeather.clear();
        mListEmoji.clear();
        mListCollections.clear();
        mListColor.clear();
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_PHOTO, true));
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_SHUFFLE, true));
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_EMOJI, true));
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_WEATHER, true));
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_ASTRONOMY, true));
        mListShortcut.add(new ItemSetting(ItemSetting.TYPE_ICON_COLOR, true));

        File folder = new File("/system/media/wallpaper");
        orderByName("/system/media/wallpaper/", true, false);
		
        /*File[] fileArray = folder.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                if (pathname.getName().startsWith("thumb_")) {
                    return true;
                }
                return false;
            }
        });*/

        if (mFileWallpaper != null) {
            int split = mFileWallpaper.size() / 5;
            int mod = mFileWallpaper.size() % 5;
            for (int i = 0; i < 5; i++) {
                int max = i == 4 ? split + mod : split;
                for (int j = 0; j < max; j++) {
                    int index = i * split + j;
                    if (index < mFileWallpaper.size()) {
//                        int id = i * split + j;
                        File file = mFileWallpaper.get(i * split + j);
//                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        String path = file.getAbsolutePath().replace("thumb_", "wallpaper_");
                        //Log.d(TAG, "[initAllData] path: "+path+", AbsolutePath : "+file.getAbsolutePath()+", itemIndex = "+id);
                        switch (i) {// ItemSetting(int type, Bitmap bitmap, int overlayResId, String path, boolean thumb) {
                            case 0:
                                mListFeatured.add(new ItemSetting(ItemSetting.TYPE_FEATURED, file.getAbsolutePath(), path, R.drawable.ip_icon_new_wallpaper_time_date, false));
                                break;
                            case 1:
                                mListWeather.add(new ItemSetting(ItemSetting.TYPE_WEATHER, file.getAbsolutePath(), path, R.drawable.ip_icon_new_wallpaper_time_date, false));
                                break;
                            case 2:
                                mListEmoji.add(new ItemSetting(ItemSetting.TYPE_EMOJI, file.getAbsolutePath(), path, R.drawable.ip_icon_new_wallpaper_time_date, false));
                                break;
                            case 3:
                                mListCollections.add(new ItemSetting(ItemSetting.TYPE_COLLECTIONS, file.getAbsolutePath(), path, R.drawable.ip_icon_new_wallpaper_time_date, false));
                                break;
                            case 4:
                                mListColor.add(new ItemSetting(ItemSetting.TYPE_COLOR, file.getAbsolutePath(), path, R.drawable.ip_icon_new_wallpaper_time_date, false));
                                break;
                        }
                    }
                }
            }
        }
    }

	/*
    private static class IconData {

        static final int TYPE_ICON = 1;
        static final int TYPE_WALLPAPER = 2;

        int mType;
        String mTitle;
        int mIconResId = -1;
        int mIconOverlayResId = -1;
        Bitmap mIconBitmap;
        String mFilePath;
        Intent mIntent;

        public IconData(String title, int iconResId, Intent intent) {
            mType = TYPE_ICON;
            mTitle = title;
            mIconResId = iconResId;
            mIntent = intent;
        }

        public IconData(String title, Bitmap bitmap, int overlayResId, String path) {
            mType = TYPE_WALLPAPER;
            mTitle = title;
            mIconBitmap = bitmap;
            mIconOverlayResId = overlayResId;
            mFilePath = path;
        }
    }*/

    private static class IconHolder extends RecyclerView.ViewHolder {

        TextView mViewTitle;
        ImageView mViewIcon;
        ImageView mViewIconOverlay;

        public IconHolder(View itemView) {
            super(itemView);
            mViewTitle = (TextView) itemView.findViewById(android.R.id.title);
            mViewIcon = (ImageView) itemView.findViewById(android.R.id.icon);
            mViewIconOverlay = (ImageView) itemView.findViewById(android.R.id.icon1);
        }
    }

    private static class IconAdapter extends RecyclerView.Adapter<IconHolder> {

        private final List<ItemSetting> mList;

        public IconAdapter(List<ItemSetting> dataList) {
            mList = dataList;
        }

        @Override
        public IconHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = View.inflate(parent.getContext(), R.layout.lock_add_new_wallpaper_item, null);
            return new IconHolder(itemView);
        }

        @Override
        public void onBindViewHolder(IconHolder holder, int position) {
            ItemSetting data = mList.get(position);
            //Log.d(TAG, "[onBindViewHolder] isIcon = "+data.getIsIcon()+", ThumPath : "+data.getThumPath());
            if (data.getIsIcon()) {
                holder.mViewTitle.setText(data.getTitle());
                if (data.getIconResId() != -1) {
                    holder.mViewIcon.setImageResource(data.getIconResId());
                }
                holder.mViewIconOverlay.setVisibility(View.GONE);
				/*
                if (data.mIntent != null) {
                    holder.mViewIcon.setTag(data.mIntent);
                    holder.mViewIcon.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Object obj = v.getTag();
                            if (obj instanceof Intent) {
                                v.getContext().startActivity((Intent) obj);
                            }
                        }
                    });
                }*/
            } else {
                if (data.getTitle() != -1) {
                    holder.mViewTitle.setText(data.getTitle());
                    holder.mViewTitle.setVisibility(VISIBLE);
                } else {
                    holder.mViewTitle.setVisibility(GONE);
                }
                if (data.getIconOverlayResId() != -1) {
                    holder.mViewIconOverlay.setImageResource(data.getIconOverlayResId());
                    holder.mViewIconOverlay.setVisibility(VISIBLE);
                } else {
                    holder.mViewIconOverlay.setVisibility(GONE);
                }
                holder.mViewIcon.setTag(data);
                Bitmap bitmap = BitmapFactory.decodeFile(data.getThumPath());
                holder.mViewIcon.setImageBitmap(bitmap);
                holder.mViewIcon.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Object obj = v.getTag();
                        if (obj instanceof ItemSetting) {
                            onItemClicked((ItemSetting) obj);
                        }
                    }
                });
            }
        }

        public void onItemClicked(ItemSetting data) {

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        @Override
        public int getItemViewType(int position) {
            return mList.get(position).getIsIcon() ? 1 : 2;
        }
    }

    public void setOnAddCallback(SettingViewItemCallback cb) {
        mAddCallback = cb;
    }

}
